﻿using GameDataTempshitEditor.Widgets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameDataTempshitEditor.DataEditors
{
    /// <summary>
    /// A selector for named objects
    /// </summary>
    public class GameData_PropertyEditor_ObjectList : PropertyItemEditor_Choice
    {
        private readonly Red.GameData.Raw.ReflectionClass _BaseClass;

        private readonly Red.GameData.Raw.ReflectionData _RootReflection;
        private readonly Red.GameData.Raw.DataCollection _RootDataCollection;

        public GameData_PropertyEditor_ObjectList(PropertyItemBase Item, Red.GameData.Raw.ReflectionClass baseClass, Red.GameData.Raw.ReflectionData rootReflection, Red.GameData.Raw.DataCollection rootData)
            : base(Item)
        {
            _BaseClass = baseClass;
            _RootReflection = rootReflection;
            _RootDataCollection = rootData;
        }

        public override void GetOptions(ref List<ComboOption> options)
        {
            var objectList = _RootDataCollection.ExtractNamedObjectList(_BaseClass.Name, _BaseClass.KeyName, _RootReflection);
            foreach (var str in objectList)
            {
                if (!str.RawData.IsAbstract)
                {
                    var guidText = Red.GameData.Raw.Utils.FormatGuid(str.RawData.ID); // note, that we display different value than we set
                    var displayName = str.ClassName + ": '" + str.Name + "'";
                    options.Add(new ComboOption(displayName, guidText));
                }
            }

            options.OrderBy(o => o.DisplayName);
        }

        public override bool ValidateValue(string value, ref string errorMessage)
        {
            Guid parsedGuid = Guid.Empty;
            if (!Red.GameData.Raw.Utils.ParseGuid(value, ref parsedGuid))
            {
                errorMessage = "Unable to parse a valid GUID from '" + value + "'";
                return false;
            }

            return true;
        }
    }
}
